<html>
<head>
<title>User-Agent switcher configuration</title>
<link rel="stylesheet" type="text/css" href="css/spoofer.css" />
<link href='http://fonts.googleapis.com/css?family=Droid+Sans:400,600' rel='stylesheet' type='text/css'>
<script src="js/spoofer.js"></script>
<script src="js/jquery.js"></script>
</head>
<script type="text/javascript">
var preset_options = [];

function saveUseBuiltInListCheckbox() {
	setShouldUsePresets($("#builtin").prop("checked"));
	if (shouldUsePresets()) setStatus("Now using built-in list.");
	else setStatus("No longer using built-in list.");
}

function refreshBuiltInListCheckbox() {
	$("#builtin").prop("checked", shouldUsePresets());
}

function setList(list) {
	// Verify that the list exists, and is the proper format.
	setSpoofList(list);
	chrome.extension.sendRequest({
		action: "update"
	}, function (response) {});
}

function getList() {
	var list = getSpoofList();
	chrome.extension.sendRequest({
		action: "update"
	}, function (response) {});
	if (!list || typeof list == "undefined") {
		list = new Array();
	}
	console.log(list);
	return list;
}

function resetHardcodedUserAgents() {
	getBaseOptionsList(true);
	restoreOptions();
	menuItemChange($('.menu_controlled:first'), $('.menuitem:first'));
}

function guessGroup() {
	if ($("#add_ua_group").val() == "") {
		var guess = guessUserAgentGroup($("#add_ua_user_agent").val());
		if (guess != "") $("#add_ua_group").attr("value", guess);
		else {
			guess = guessUserAgentGroup($("#add_ua_name").val())
			if (guess != "") $("#add_ua_group").attr("value", guess);
		}
	}
}

function setStatus(status) {
	// TODO(gwilson): Need to determine how best to show the status.
	// $("#status").text(status);
}

function addOption() {
	var list = getList();
	var new_option = new PresetSpoof($("#add_domain").val(), new UserAgent("title", $("#add_ua").val(), "vendor", "badge", false));
	if (new_option.domain == "" || new_option.user_agent.ua_string == "") {
		setStatus("All fields are required.");
		$("#add_domain").toggleClass("error", true);
		$("#add_ua").toggleClass("error", true);
		return;
	}

	chrome.extension.sendRequest({
		action: "add_preset",
		domain: document.getElementById("add_domain").value,
		option_index: $("#options").prop("selectedIndex")
	}, function (response) {
		restoreOptions();
	});
	setStatus("Blacklist entry added.");
	$("#add_domain").attr("value", "");
	$("#add_ua").attr("value", "");
}

// Adds the option currently entered into the input fields to the list of
// custom user-agents.


function addUAOption() {

	if ($("#add_ua_name").val() == "" || $("#add_ua_user_agent").val() == "" || $("#add_ua_indicator").val() == "") {

		setStatus("All fields are required.");

		$("#add_ua_name").toggleClass("error", true);
		$("#add_ua_user_agent").toggleClass("error", true);
		$("#add_ua_indicator").toggleClass("error", true);
		return;
	}
	addCustomUAOption($("#add_ua_name").val(), $("#add_ua_user_agent").val(), ($("#add_ua_is_append").val() == "true"), $("#add_ua_indicator").val(), $("#add_ua_group").val());
	restoreOptions();
}

function populateTextFromDropdown() {
	$("#add_ua").attr("value", $('#options option:selected').val());
}

function refreshPresetOptions() {
	chrome.extension.sendRequest({
		action: "options"
	}, function (response) {
		preset_options = JSON.parse(response.options);
		var select = $("#options");
		if (select) for (var i = 0; i < preset_options.length; i++) {
			if (preset_options[i].ua_string != "") {
				var option = document.createElement("option");
				option.setAttribute("value", preset_options[i].ua_string);
				option.appendChild(document.createTextNode(preset_options[i].title));
				select.append(option);
			}
		}
	});
}

function refreshPresetUserAgentOptions() {
	var options_map = getOptionsByGroup();
	var table = $("#ua_list_table");
	for (group in options_map) {
		table.append(getUATitleRow((group == "" ? "[No group]" : group)));
		var list = options_map[group];
		var sub_table = document.createElement("table");
		sub_table.setAttribute("id", "ua_list_sub_table_" + group);
		sub_table.setAttribute("class", "ua_list_sub_table");
		for (var i = 0; i < list.length; i++) {
			sub_table.appendChild(addUARow(list[i]));
		}
		var tr = document.createElement("tr");
		var td = document.createElement("td");
		td.appendChild(sub_table);
		tr.appendChild(td);
		table.append(tr);
	}
}

function getUATitleRow(group_name) {
	var tr = document.createElement("tr");
	var td = document.createElement("td");
	td.setAttribute("class", "ua_title_row");
	td.appendChild(document.createTextNode(group_name));
	tr.appendChild(td);
	return tr;
}

function _getOptionsDropdown() {
	var select = document.createElement("select");
	select.setAttribute("id", "options");
	select.addEventListener("change", populateTextFromDropdown, false);
	var option = document.createElement("option");
	option.setAttribute("value", "");
	option.appendChild(document.createTextNode(""));
	select.appendChild(option);
	return select;
}

function addRow(elem1, elem2, elem3, elem4, no_delete_button) {
	var deletebutton = document.createElement("div");
	deletebutton.setAttribute("alt", "delete");
	deletebutton.setAttribute("border", "0");
	deletebutton.setAttribute("class", "deletebutton");
	deletebutton.setAttribute("onclick", "deleteOption('" + elem1 + "');");
	return _newRow([document.createTextNode(elem1),
		                 document.createTextNode(elem2),
		                 document.createTextNode(elem3),
		                 (elem4 ? document.createTextNode(elem4) : null),
		                 (no_delete_button ? document.createTextNode("") : deletebutton)]);
}

function addUARow(user_agent) {

	var deletebutton = document.createElement("div");
	deletebutton.setAttribute("class", "deletebutton");
	deletebutton.setAttribute("border", "0");
	deletebutton.setAttribute("alt", "delete");
	deletebutton.setAttribute("onclick", "deleteUAOption('" + user_agent.title + "', eval('" + user_agent.is_preset + "'));");
	return _newRow([document.createTextNode(user_agent.title),
		                 document.createTextNode(getDisplayUserAgentString(user_agent)),
		                 document.createTextNode(getDisplayAppendOrReplaceString(user_agent)),
		                 document.createTextNode(user_agent.badge),
		                 (isRemovable(user_agent) ? deletebutton : document.createTextNode(""))]);
}

function _newRow(nodes) {
	var tr = document.createElement("tr");
	for (var i = 0; i < nodes.length; i++) {
		if (!nodes[i]) continue;
		var td = document.createElement("td");
		td.appendChild(nodes[i]);
		tr.appendChild(td);
	}
	return tr;
}

function addTitleRow() {
	var row = _newRow([document.createTextNode("Domain"),
		                    document.createTextNode("User-Agent String"),
		                    document.createTextNode(""),
		                    document.createTextNode("")]);
	row.setAttribute("class", "title");
	return row;
}

function addUATitleRow() {
	var row = _newRow([document.createTextNode("New User-agent name"),
		                    document.createTextNode("New User-Agent String"),
		                    document.createTextNode("Group"),
		                    document.createTextNode("Append?"),
		                    document.createTextNode("Indicator Flag"),
		                    document.createTextNode("")]);
	row.setAttribute("class", "title");
	return row;
}

function addNewEntryRow() {
	var add_ua = document.createElement("input");
	var add_vendor = document.createTextNode("");
	var add_domain = document.createElement("input")
	add_ua.setAttribute("id", "add_ua");
	add_ua.setAttribute("type", "hidden"); // This is here for testing.
	add_domain.setAttribute("id", "add_domain");

	var addbutton = document.createElement("input");
	addbutton.type = "button";
	addbutton.setAttribute("onclick", "addOption();");
	addbutton.setAttribute("id", "add_entry_button");
	addbutton.value = "Add";

	var span = document.createElement("span");
	span.appendChild(add_ua);
	span.appendChild(_getOptionsDropdown());

	return _newRow([add_domain, span, add_vendor, addbutton]);
}

function addNewUAEntryRow() {
	var add_ua_name = document.createElement("input");
	var add_ua_indicator = document.createElement("input");
	var add_ua_is_append = document.createElement("select");
	var add_ua_user_agent = document.createElement("input");
	var add_ua_group = document.createElement("input");

	add_ua_name.setAttribute("id", "add_ua_name");
	add_ua_name.setAttribute("onchange", "guessGroup();");

	add_ua_indicator.setAttribute("id", "add_ua_indicator");

	add_ua_user_agent.setAttribute("id", "add_ua_user_agent");
	add_ua_user_agent.setAttribute("onchange", "guessGroup();");

	add_ua_indicator.setAttribute("maxlength", "3");
	add_ua_indicator.setAttribute("size", "3");

	add_ua_is_append.setAttribute("id", "add_ua_is_append");

	add_ua_group.setAttribute("id", "add_ua_group");

	var add_ua_is_append_replace_option = document.createElement("option");
	add_ua_is_append_replace_option.setAttribute("value", "false");
	add_ua_is_append_replace_option.appendChild(document.createTextNode("Replace"));
	add_ua_is_append.appendChild(add_ua_is_append_replace_option);

	var add_ua_is_append_append_option = document.createElement("option");
	add_ua_is_append_append_option.setAttribute("value", "true");
	add_ua_is_append_append_option.appendChild(document.createTextNode("Append"));
	add_ua_is_append.appendChild(add_ua_is_append_append_option);

	var addbutton = document.createElement("input");
	addbutton.type = "button";
	addbutton.setAttribute("id", "add_ua_button");
	addbutton.setAttribute("onclick", "addUAOption();");
	addbutton.value = "Add";

	return _newRow([add_ua_name,
		                 add_ua_user_agent,
		                 add_ua_group,
		                 add_ua_is_append,
		                 add_ua_indicator,
		                 addbutton]);
}

function deleteOption(domain) {
	var list = getList();
	// Find the domain specified, delete it from the list and re-save the list.
	for (var i = 0; i < list.length; i++) {
		if (list[i].domain == domain) {
			list.splice(i, 1);
			break;
		}
	}
	setList(list);
	setStatus("Spooflist entry deleted.");
	restoreOptions();
}

function deleteUAOption(name, is_base_option) {
	var action = (is_base_option ? "delete_base_ua" : "delete_ua");
	chrome.extension.sendRequest({
		action: action,
		name: name
	}, function (response) {
		if (response.result == "success") setStatus("User-agent deleted successfully.");
		else setStatus("User-agent deletion FAILED.");
		restoreOptions();
	});
}

// Regenerates the current view from the saved state.


function restoreOptions() {
	var list = getList();

	var table = $("#list_table");
	if (table) table.replaceWith(document.createElement("table"));

	table = $("#tablecontainer table");
	table.prop("id", "list_table");
	table.append(addTitleRow());
	table.append(addNewEntryRow());
	for (var i = 0; i < list.length; i++) {
		var entry = list[i];
		var tr = addRow(entry.domain, entry.user_agent.ua_string, ""); // Last item is legacy.
		table.append(tr);
	}
	table = $("#ua_add_table");
	table.empty();
	var extra_row = addUATitleRow();
	extra_row.setAttribute("class", "ua_list_sub_table");
	table.append(extra_row);
	extra_row = addNewUAEntryRow();
	extra_row.setAttribute("class", "ua_list_sub_table");
	table.append(extra_row);

	table = $("#ua_list_table");
	table.empty();

	refreshPresetUserAgentOptions();
	refreshPresetOptions();
	refreshBuiltInListCheckbox();
}

function menuItemChange(item_to_show, item_to_highlight) {
	$('.menu_controlled').addClass("invisible");
	item_to_show.removeClass("invisible");

	$('.menuitem').removeClass("selected");
	item_to_highlight.addClass("selected")
}

function handleFileSelect(evt) {
	var files = evt.target.files; // FileList object
	for (var i = 0, f; f = files[i]; i++) {
		var reader = new FileReader();

		reader.onload = (function (theFile) {
			return function (e) {
				importUserAgentData(e.target.result);
			};
		})(f);

		reader.readAsText(f);
	}
}

</script>
</head>
<body onload="restoreOptions(); menuItemChange($('.menu_controlled:first'), $('.menuitem:first'));">
<table id="outer">
  <tr>
    <td width="1%">
      <table id="menu" class="menu">
        <tr>
          <td>
            <table class="logo">
              <tr>
                <td rowspan="2">
                  <img width="48" height="48" src="images/spoofer-128.png" border="0">
                </td>
              </tr>
              <tr>
                <td class="logo">
                  User-Agent Switcher<br>for Chrome
                </td>
              </tr>
            </table>
          </td>
        </tr>
        <tr>
          <td class="menuitem" onClick="menuItemChange($('#custom_ua_table'), $(this))">
            Custom User-Agents
          </td>
        </tr>
        <tr>
          <td class="menuitem" onClick="menuItemChange($('#permanent_spoof_table'), $(this))">
            Permanent Spoof list
          </td>
        </tr>
        <!--
        <tr>
          <td class="menuitem" onClick="menuItemChange($('#import_table'), $(this))">
            Import Settings
          </td>
        </tr>
        -->
        <tr>
          <td class="menuitem" onClick="menuItemChange($('#other_settings_table'), $(this))">
            Other Settings
          </td>
        </tr>
        <tr>
          <td class="menuitem" onClick="menuItemChange($('#about_table'), $(this))">
            About
          </td>
        </tr>
      </table>
    </td>
    <td>
      &nbsp;&nbsp;
    </td>
    <td>
      <!--
      <table id="status_table">
        <tr>
          <td>
            <span id="status"></span>
            <br>
          </td>
        </tr>
      </table>
      <br>-->
      <table id="custom_ua_table" class="menu_controlled">
        <tr>
          <td colspan="2">
            <div class="subheader">Custom User-Agent List</div><br><br>
            <div id="ua_tablecontainer" class="tablecontainer">
              <table id="ua_add_table" class="list_table">
              </table>
              <table id="ua_list_table" class="list_table">
              </table>
            </div>
            <br>
          </td>
        </tr>
      </table>
      <table id="other_settings_table" class="menu_controlled">
        <tr>
          <td colspan="2" class="tablecontainer">
            <div class="subheader">Other Settings</div><br>
            <table class="other_options">
              <tr>
                <td rowspan="2" align="right">
                  <input type="checkbox" value="1" name="builtin" id="builtin" onChange="saveUseBuiltInListCheckbox();">
                </td>
                <td class="bold">
                  Use and auto-update the User-Agent switcher's built-in spoofing list.
                </td>
              </tr>
              <tr>
                <td>
                   Automatically switch user-agent and vendor strings for sites in the User-Agent spoofer's known incompatibility list.
                   Also attempt to auto-update the list from spoofer-extension.appspot.com once per day.<br><br>
                   If this box is unchecked, the extension will not attempt to update its pre-set spoof ("known offender") list and will not
                   spoof any sites you don't specify yourself.<br><br>
                </td>
              </tr>
              <tr>
                <td rowspan="2" align="right">
                  <input type="button" onClick="resetHardcodedUserAgents();" value="Reset">
                </td>
                <td class="bold">
                  Reset "known" user-agent strings.
                </td>
              </tr>
              <tr>
                <td>
                  Resets the list of "known" user-agent strings, in case some were deleted that you want to get back.
                </td>
              </tr>
            </table>
          </td>
        </tr>
      </table>
      <table id="import_table" class="menu_controlled">
        <tr>
          <td colspan="2" class="tablecontainer">
            <div class="subheader">Import Settings</div><br>
            <table class="other_options">
              <tr>
                <td>
                  Import user-agent strings from a local, comma-separated value file:
                </td>
              </tr>
              <tr>
                <td>
                  <input type="file" name="import_file" id="local_file_import">
                  <script>
                    document.getElementById('local_file_import').addEventListener('change', handleFileSelect, false);
                  </script>
                </td>
              </tr>
              <!--
              <tr>
                <td>
                  Import user-agent strings from a comma-separated value file at URL:
                </td>
              </tr>
              <tr>
                <td>
                  <input type="text"> <input type="button" value="import">
                </td>
              </tr>
              -->
            </table>
          </td>
        </tr>
      </table>
      <table id="about_table" class="menu_controlled">
        <tr>
          <td colspan="2" class="tablecontainer">
            <div class="subheader">About</div><br>
            <table>
               <tr>
                 <td>
                  The User-Agent Switcher for Chrome is a Chrome extension that
                  allows you to quickly and easily modify Chrome's user-agent
                  while browsing.  It also allows you to set up permanent
                  user-agent switching behavior so that Chrome will always use
                  a different user-agent string for certain sites.
                  <br><br>
                  This extension is built and maintained by <a target="_new" href="https://plus.google.com/105199364823220402760">Glenn Wilson</a>.
                  <br><br>
                  More information about this extension is available at
                  <a href="http://spoofer-extension.appspot.com/">spoofer-extension.appspot.com</a>
                  <br><br>
                  All references to other browsers are the trademarks and property of their respective owners.<br>
                 </td>
               </tr>
            </table>
          </td>
        </tr>
      </table>
      <table id="permanent_spoof_table" class="menu_controlled">
        <tr>
          <td colspan="2">
            <div class="subheader">Permanent Spoof List</div><br><br>
            <div id="tablecontainer" class="tablecontainer">
              <table id="list_table" class="list_table">
              </table>
            </div>
            <br>
          </td>
        </tr>
      </table>
    </td>
  </tr>
</table>
</body>
</html>